﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Collections;
using System.Configuration;
namespace AteckCsharp.Account
{
    public partial class ManageUsers : System.Web.UI.Page
    {
        private void CreatePopUpMessage(string message)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", message, true);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindRolesToList();
                //Check the selected user's roles 
                CheckRolesForSelectedUser();
            }
        }
        protected void RoleCheckBox_CheckChanged(object sender, EventArgs e)
        {
            // Reference the CheckBox that raised this event 
            System.Web.UI.WebControls.CheckBox RoleCheckBox = sender as System.Web.UI.WebControls.CheckBox;


            // Get the currently selected user and role 
            string selectedUserName = Session["customer_name"].ToString();
            //Get the User Current Roles.
            string[] currRole = Roles.GetRolesForUser(selectedUserName);
           

            string roleName = RoleCheckBox.Text;

            // Determine if we need to add or remove the user from this role 
            if (RoleCheckBox.Checked)
            {//Remove the user from all the roles first.
                try
                {
                    for (int ro = 0; ro < currRole.Length; ro++)
                    {
                        Roles.RemoveUserFromRole(selectedUserName, currRole[ro]);
                    }
                }
                catch (Exception ex)
                {
                    DisableCheckBoxes();
                    return;
                }
                 
                // Add the user to the role 
                Roles.AddUserToRole(selectedUserName, roleName);
                // Display a status message 
                // ActionStatus.Text = string.Format("User {0} was added to role {1}.", selectedUserName, roleName);
            }
            else
            {
                // Remove the user from the role 
                Roles.RemoveUserFromRole(selectedUserName, roleName);
                // Display a status message 
                //  ActionStatus.Text = string.Format("User {0} was removed from role {1}.", selectedUserName, roleName);

            }
            DisableCheckBoxes();
            BindRolesToList();
            //Check the selected user's roles 
            CheckRolesForSelectedUser();
        }
        private void DisableCheckBoxes()
        {
            for (int i = 0; i <= GridView2.Rows.Count - 1; i++)
            {
                Repeater rep = new Repeater();
                rep = (Repeater)GridView2.Rows[i].Cells[1].FindControl("UsersRoleList");
                foreach (RepeaterItem repi in rep.Items)
                {
                    System.Web.UI.WebControls.CheckBox checkBox = new System.Web.UI.WebControls.CheckBox();
                    checkBox = (System.Web.UI.WebControls.CheckBox)repi.FindControl("RoleCheckBox");
                    checkBox.Enabled = false;
                }
            }
        }
        ///<summary>
        ///this function check the role of each user in database and 
        ///put a check mark next to everyuser
        ///</summary>
        private void CheckRolesForSelectedUser()
        {
            //Loop through the grid view and get the user names indatabase to send it and get 
            //the roles assigned to each user
            for (int i = 0; i <= GridView2.Rows.Count - 1; i++)
            {
                string user_name = GridView2.Rows[i].Cells[0].Text;


                // Determine what roles the selected user belongs to 
                Repeater rept = new Repeater();
                rept = (Repeater)GridView2.Rows[i].Cells[1].FindControl("UsersRoleList");
                string[] selectedUsersRoles = Roles.GetRolesForUser(user_name);

                // Loop through the Repeater's Items and check or uncheck the checkbox as needed 

                foreach (RepeaterItem ri in rept.Items)
                {
                    // Programmatically reference the CheckBox 
                    System.Web.UI.WebControls.CheckBox RoleCheckBox = ri.FindControl("RoleCheckBox") as System.Web.UI.WebControls.CheckBox;
                    // See if RoleCheckBox.Text is in selectedUsersRoles 
                    if (selectedUsersRoles.Contains<string>(RoleCheckBox.Text))
                    {
                        RoleCheckBox.Checked = true;
                        RoleCheckBox.Enabled = false;
                    }
                    else
                    {
                        RoleCheckBox.Checked = false;
                        RoleCheckBox.Enabled = false;
                    }
                }

            }
        }
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

            // foreach (DictionaryEntry entry in e.NewValues)
            //{
            try
            {


                object[] keys = (object[])Array.CreateInstance(typeof(object), e.NewValues.Count);
                e.NewValues.Keys.CopyTo(keys, 0);

                foreach (object key in keys)
                {
                    e.NewValues[key] = Server.HtmlEncode(e.NewValues[key].ToString());
                }
                //e.NewValues[entry.Key] = Server.HtmlEncode(entry.Value.ToString());

                // }
            }
            catch (Exception ex)
            {
                CreatePopUpMessage("alert('did not work')");
            }

        }

        private void BindRolesToList()
        {

            // Get all of the roles 
            string[] roles = Roles.GetAllRoles();

            Repeater rept = new Repeater();
            for (int i = 0; i <= GridView2.Rows.Count - 1; i++)
            {

                rept = (Repeater)GridView2.Rows[i].Cells[1].FindControl("UsersRoleList");
                rept.DataSource = roles;
                rept.DataBind();
            }
        }
       
        protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session.Remove("customer_name");
            GridViewRow row = GridView2.SelectedRow;
            string customer_name = row.Cells[0].Text;
            Session.Add("customer_name", customer_name);

            Repeater rep = new Repeater();
            rep = (Repeater)GridView2.SelectedRow.Cells[1].FindControl("UsersRoleList");
            foreach (RepeaterItem repi in rep.Items)
            {
                System.Web.UI.WebControls.CheckBox checkBox = new System.Web.UI.WebControls.CheckBox();
                checkBox = (System.Web.UI.WebControls.CheckBox)repi.FindControl("RoleCheckBox");
                checkBox.Enabled = true;
            }
        }
    }
}